package com.reserv.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.reserv.dao.ServiceDAO;
import com.reserv.vo.ServiceVO;


public class QuickReservServlet extends HttpServlet {
	private ServiceDAO dao;
	@Override
	public void init(ServletConfig config) throws ServletException {
		dao = ServiceDAO.getInstance();

	}
	private void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		Gson gson = new Gson();

		String type = request.getParameter("type");
		String local = request.getParameter("local");
		String kind = request.getParameter("kind");
		int step = Integer.parseInt(request.getParameter("step"));

		if(step == 0) {
			ArrayList<String> list = (ArrayList<String>) dao.getTypeList();
			ArrayList<String> jsonList = new ArrayList<>();
			for(String str : list) {
				str = URLEncoder.encode(str, "utf-8");
				jsonList.add(str);
			}
			String json = gson.toJson(jsonList);
			out.print(json);
			
		} else if(step == 1) {
			ArrayList<String> list = (ArrayList<String>) dao.getLocalList(type);
			ArrayList<String> jsonList = new ArrayList<>();
			for(String str : list) {
				str = URLEncoder.encode(str, "utf-8");
				jsonList.add(str);
			}
			String json = gson.toJson(jsonList);
			out.print(json);

		} else if(step == 2) {
			ArrayList<String> list = (ArrayList<String>) dao.getKindList(type, local);
			ArrayList<String> jsonList = new ArrayList<>();
			for(String str : list) {
				str = URLEncoder.encode(str, "utf-8");
				jsonList.add(str);
			}
			String json = gson.toJson(jsonList);
			out.print(json);

		} else if(step == 3) {
			ArrayList<ServiceVO> list = (ArrayList<ServiceVO>) dao.getServiceList(type, local, kind);
			for(ServiceVO s : list) {
				s.setTitle(URLEncoder.encode(s.getTitle(), "utf-8"));
			}
			
			String json = gson.toJson(list);
			out.println(json);
			
		} else if(step == 4) {
			int sno = Integer.parseInt(request.getParameter("sno"));
			ServiceVO s = dao.getVO(sno);
			
			s.setTitle(URLEncoder.encode(s.getTitle(), "utf-8"));
			
			String json = gson.toJson(s);
			out.println(json);
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}
}
